Skip to main content

Remove Nth Node From End of List

LeetCode 19 | Difficulty: Medium​

Medium

Problem Description​

Given the head of a linked list, remove the n^th node from the end of the list and return its head.

Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

- The number of nodes in the list is `sz`.

- `1 <= sz <= 30`

- `0 <= Node.val <= 100`

- `1 <= n <= sz`

Follow up: Could you do this in one pass?

Topics: Linked List, Two Pointers


Approach​

Linked List​

Use pointer manipulation. Common techniques: dummy head node to simplify edge cases, fast/slow pointers for cycle detection and middle finding, prev/curr/next pattern for reversal.

When to use

In-place list manipulation, cycle detection, merging lists, finding the k-th node.


Solutions​

Solution 1: C# (Best: 169 ms)​

MetricValue
Runtime169 ms
MemoryN/A
Date2017-08-01
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode start = new ListNode(-1);
ListNode slow = start, fast = start;
slow.next = head;

for (int i = 0; i <= n; i++)
{
fast = fast.next;
}
while (fast != null )
{
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;

return start.next;
}
}

Complexity Analysis​

ApproachTimeSpace
Two Pointers$O(n)$$O(1)$
Linked List$O(n)$$O(1)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Draw the pointer changes before coding. A dummy head node simplifies edge cases.
  • LeetCode provides 1 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: Maintain two pointers and update one with a delay of n steps.